package br.org.imazon.sad;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.google.gdata.client.ClientLoginAccountType;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.GoogleAuthTokenFactory.UserToken;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;


@SuppressWarnings("serial")
public class AuthServlet extends HttpServlet {
		
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    try {
      Authenticate.auth(req.getSession(), req.getParameter("service"));
      RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/authPage.jsp");
      rd.forward(req, resp);
    } catch (Exception e) {
      throw new ServletException("Servlet caught a ServletException: " + e.getMessage());
    }
  }

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		
		String email = req.getParameter("email");
		String password = req.getParameter("password");
		String services = req.getParameter("services");
		String authReturn = "no results";
		
		
		if (email != null && password != null &&
				email.length() > 0 && password.length() > 0) {
			
			String[] serviceArray = services.split(",");
			String service;
			for (int i = 0; i < serviceArray.length; i++) {
				service = serviceArray[i];
				PersistenceManager pm = PMF.get().getPersistenceManager();
				
				GoogleService gService = new GoogleService(service, service + ".imazonsad");
				
				try {
					gService.setUserCredentials(email, password, ClientLoginAccountType.GOOGLE);
					UserToken authToken = (UserToken) gService.getAuthTokenFactory().getAuthToken();
					
					AuthModel authModel = new AuthModel(email, authToken.getValue(), service);
					
					// 
				     try {
				            pm.makePersistent(authModel);
				            if(Authenticate.auth(req.getSession(), service) == null) {
				            	authReturn = null;
				            } else if (authReturn.equals("no results")) {
				            	authReturn = "results";
				            }
	
				        } finally {
				            pm.close();
				        }
				} catch (AuthenticationException e) {
					// TODO Auto-generated catch block
					System.out.println("can't get auth token " + e.getStackTrace().toString());
				}
			}
		}
				 try {
				      if ((authReturn != null) && (!(authReturn.equals("no results")))) {
				        RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/authPage.jsp");
				        rd.forward(req, resp);
				      } else {
				        RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/authError.jsp");
				        rd.forward(req, resp);
				      }
				    } catch (Exception e) {
				    	throw new ServletException("Servlet caught a ServletException: " + e.getMessage());
				    }

			
		
		//if (authSuccess != null) {
	//		resp.sendRedirect("/authPage.jsp");	
	//	} else {
	//		resp.sendRedirect("/authError.jsp");
	//	}
	}
	
	
	
}
